package com.lean.pulltorefresh.list;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import com.lean.pulltorefresh.R;
import com.lean.pulltorefresh.list.base.PullToRefreshView;
import com.lean.pulltorefresh.view.HorizontalProgressDrawable;
import com.lean.pulltorefresh.view.PullToRefreshProgressDrawable;

/**
 * Created by Lean·He on 16/7/28.
 */
public class ProgressListView extends PullToRefreshView {

    private final int MAX_SIZE = 100;
    private View headView;
    private View footerView;
    private HorizontalProgressDrawable headerProgressBar;

    public ProgressListView(Context context) {
        this(context, null);
    }

    public ProgressListView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ProgressListView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        headView = LayoutInflater.from(getContext()).inflate(R.layout.progress_head_view, null, false);
        footerView = LayoutInflater.from(getContext()).inflate(R.layout.view_loading_more, null, false);
        ((PullToRefreshProgressDrawable) footerView.findViewById(R.id.loading_more_drawable)).start();
        headView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, 0));
        headerProgressBar = (HorizontalProgressDrawable) headView.findViewById(R.id.loading_progress_drawable);
        addHeaderView(headView);
    }

    @Override
    protected void updateHeaderView(int paddingTop) {
        float present = 1 - paddingTop * 1.0f / MAX_SIZE;
        headerProgressBar.setProgress(present);
    }

    @Override
    protected void onPullToRefresh() {
        super.onPullToRefresh();
        headerProgressBar.setVisibility(View.VISIBLE);
    }

    @Override
    protected void onReleaseToRefresh() {
        super.onReleaseToRefresh();
    }

    @Override
    protected void onRefreshing() {
        super.onRefreshing();
        headerProgressBar.setVisibility(View.VISIBLE);
        headerProgressBar.start();
    }

    @Override
    protected void onReset() {
        super.onReset();
        headerProgressBar.setVisibility(View.VISIBLE);
        headerProgressBar.stop();
        headerProgressBar.setProgress(0);
    }

    @Override
    public boolean isDragForbidden() {
        return headerProgressBar.getProgress() != 0;
    }

    @Override
    protected View getHeaderView() {
        return headView;
    }

    @Override
    protected View getFooterView() {
        return footerView;
    }

    @Override
    public void setOnLoadMoreListener(OnLoadMoreListener onLoadMoreListener) {
        super.setOnLoadMoreListener(onLoadMoreListener);
        addFooterView(footerView);
    }

    @Override
    protected int isReadyToRefreshSize() {
        return MAX_SIZE;
    }
}